package com.evzgaga.evzrecon.plugins;

import com.evzgaga.evzrecon.annotations.CallbackHandler;
import com.evzgaga.evzrecon.annotations.Injected;
import com.evzgaga.evzrecon.annotations.Plugin;
import com.evzgaga.evzrecon.event.ChatCommandEvent;
import com.evzgaga.evzrecon.event.ServerCallbackEvent;
import com.evzgaga.evzrecon.xmlrpc.client.GbxRemoteConnection;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Bastien
 */
@Plugin
public class ChatCommandsPlugin {
    private static final int IS_REGISTERED_COMMAND_INDEX = 3;
    private static final int TEXT_INDEX = 2;
    
    @Injected(canBeNull=false)
    private GbxRemoteConnection server;
    
    @CallbackHandler(callbacks="TrackMania.PlayerChat")
    public void handlePlayerChat(ServerCallbackEvent event) {
        if (Boolean.TRUE.equals(event.callbackParams.get(IS_REGISTERED_COMMAND_INDEX))) {
            String fullCommand = (String)event.callbackParams.get(TEXT_INDEX);
            String[] parts = fullCommand.split(" ");
            ChatCommandEvent chatEvent = new ChatCommandEvent(getCommand(parts), getParameters(parts));
            server.fireChatCommandEvent(chatEvent);
        }
    }
    
    protected String getCommand(String[] parts) {
        return (parts.length > 0) ? parts[0].substring(1) : "";
    }
    
    protected List<String> getParameters(String[] parts) {
        List<String> params = new ArrayList<String>();
        
        if (parts.length > 1) {
            for (int i = 1; i < parts.length; i++) {
                params.add(parts[i]);
            }
        }
        
        return params;
    }    
}
